/*
 * @Author: C.
 * @Date: 2023-05-04 17:11:38
 */
import { unref } from 'vue';
import type { RetInstance } from '/@/components/table/src/hooks/useTableContext';
import { aoaToSheetXlsx } from '/@/components/Excel/src/Export2Excel';
import { isString, isFunction } from '/@/utils/is';
import { projectSettings } from '../../settings/projectSettings';
import type { BookType } from 'xlsx';
import { FETCH_SETTING } from '/@/components/table/src/const';
import { get, merge } from 'lodash-es';

export type IExportSourceType = 'All' | 'Filtered' | 'Current' | 'Selected';

enum ExportSourceType {
  ALL = 'All',
  FILTERED = 'Filtered',
  CURRENT = 'Current',
  SELECTED = 'Selected',
}

// 原数据 过滤

export async function export2file({
  table,
  fields = [],
  filename,
  type = 'xlsx',
  isTem = false,
  exportSource = 'Current',
  cb = () => {},
}: {
  table: RetInstance;
  fields: string[];
  filename?: string;
  type?: BookType;
  isTem?: boolean;
  exportSource: IExportSourceType;
  cb?: Fn;
}) {
  // const dataResource=table.getDataSource()
  // console.log(table, fields);
  // 表头
  const header: string[] = [];
  let data: any[] = [];
  const columnObj: any = {};
  const sortFields: string[] = [];
  table.getColumns({ ignoreAction: true, ignoreIndex: true }).forEach((item) => {
    if (fields.includes(item.dataIndex as string)) {
      header.push((item.title || item.dataIndex) as string);
      sortFields.push(item.dataIndex as string);
      columnObj[item.dataIndex as string] = item;
    }
  });
  if (!isTem) {
    try {
      let _data: Recordable<any>[] | undefined = [];
      // 'All' | 'Filtered' | 'Current' | 'Selected'
      switch (exportSource) {
        case ExportSourceType.ALL:
          // table.getProps.value.api && table.getProps.value.api({ paging: false });
          _data = await getExportData(table, exportSource);
          break;
        case ExportSourceType.FILTERED:
          _data = await getExportData(table, exportSource);
          break;
        case ExportSourceType.CURRENT:
          _data = table.getDataSource();
          break;
        case ExportSourceType.SELECTED:
          _data = table.getSelectRows();
          break;

        default:
          break;
      }

      if (!_data) {
        _data = [];
      }
      data = _data.map((item) => {
        return sortFields.map((key, index) => {
          const column = columnObj[key];
          const text = item[key];
          const record = item;

          if (column?.format) {
            const target = column.format(text, record, index, 'string');
            if (projectSettings.dataPlaceholder == target) {
              return '';
            } else if (isString(target)) {
              return target;
            } else {
              return text;
            }
          } else {
            return text;
          }
        });
      });
    } catch (error) {
      console.log(error);
      cb && cb(error);
    }
  }
  aoaToSheetXlsx({
    data,
    header,
    filename: filename,
    write2excelOpts: { bookType: type },
    cb,
  });
  // console.log(header, data, isTem, 'data');
}

async function getExportData(table: RetInstance, type: IExportSourceType) {
  const { api, searchInfo, defSort, fetchSetting, useSearchForm } = unref(table.getProps);
  if (!api || !isFunction(api)) return;
  // , totalField
  const { listField } = Object.assign({ paging: false }, FETCH_SETTING, fetchSetting);
  const params: Recordable =
    type == ExportSourceType.ALL
      ? { paging: false }
      : merge({ paging: false }, useSearchForm ? table.getFieldsValue() : {}, searchInfo, defSort);
  const res = await api(params);
  const isArrayResult = Array.isArray(res);
  const resultItems: Recordable[] = isArrayResult ? res : get(res, listField);
  // const resultTotal: number = isArrayResult ? res.length : get(res, totalField);
  return resultItems;
}
